package geektime.spring.springbucks.service;

import geektime.spring.springbucks.model.Coffee;
import geektime.spring.springbucks.repository.CoffeeRepository;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.RowBounds;
import org.joda.money.CurrencyUnit;
import org.joda.money.Money;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.List;

@Slf4j
@Service
@CacheConfig(cacheNames = {"CoffeeCache"})
public class CoffeeService {
    @Resource
    private CoffeeRepository coffeeMapper;

    @Transactional(rollbackOn = Exception.class)
    public void createCoffee() {
        Coffee latte = Coffee.builder().name("latte2").price(Money.of(CurrencyUnit.of("CNY"), 20)).build();
        Coffee cappuccino = Coffee.builder().name("latte3").price(Money.of(CurrencyUnit.of("CNY"), 30)).build();
        coffeeMapper.save(latte);
        coffeeMapper.save(cappuccino);
        log.info("插入成功2条: {}, {}", latte, cappuccino);
        log.info("插入之后总条数: {}", coffeeMapper.count());
    }

    @Transactional(rollbackOn = Exception.class)
    public void deleteById(Long id) {
         coffeeMapper.deleteById(id);
         log.info("删除成功。删除之后总条数: {}", coffeeMapper.count());
    }

    @Transactional(rollbackOn = Exception.class)
    public void updateCoffee(Long id) {
        Coffee coffee = Coffee.builder().name("latte(无糖)").build();
        coffee.setId(id);
        coffeeMapper.updateByPrimaryKeySelective(coffee);
    }

    public long count() {
        return coffeeMapper.count();
    }

    public void findAllByPage(int currentPage, int size) {

        coffeeMapper.findAllByPage(new RowBounds(currentPage, size))
                .forEach(c -> log.info("Page({}) Coffee {}", currentPage, c));
    }

    public void findAllByIds(List<Long> ids) {

        coffeeMapper.findAllByIds(ids)
                .forEach(c -> log.info("findAllByIds Coffee {}",  c));
    }

    @Cacheable(key = "#name")
    public List<Coffee> findByName(String name) {
        return coffeeMapper.findByName(name);
    }

    public void findAll() {
        coffeeMapper.findAll().forEach(c -> log.info("Coffee {}", c));
    }
}